package com.tools.ad.util;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Build;

import java.io.File;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by wanglingtao on 16/9/26.
 */
public class AppUtils {

    private static final String TAG = "AppUtils";

    private static AtomicInteger mPageCount = new AtomicInteger(0);

    public static void registerActivityLifecycleCallbacks(Context context) {
        if (Build.VERSION.SDK_INT >= 14 && context instanceof Application) {
            Application application = (Application) context;
            application.registerActivityLifecycleCallbacks(new ActivityLifeCallback() {

                @Override
                public void onActivityResumed(Activity activity) {
                    if (!activity.getComponentName().getClassName().contains("AppOuterActivity")) {
                        mPageCount.incrementAndGet();
                    }
                }

                @Override
                public void onActivityPaused(Activity activity) {
                    if (!activity.getComponentName().getClassName().contains("AppOuterActivity")) {
                        mPageCount.decrementAndGet();
                    }
                }
            });
        }
    }

    public static boolean isInSelfApp() {
        if (Build.VERSION.SDK_INT >= 14) {
            return mPageCount.get() > 0;
        }
        return false;
    }

    public static String getAppName(Context context, String packageName) {
        PackageManager pm = context.getPackageManager();
        String appName = null;
        try {
            ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);
            appName = String.valueOf(pm.getApplicationLabel(applicationInfo));
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return appName;
    }


    public static Drawable getAppIcon(Context context, String packageName) {
        PackageManager pm = context.getPackageManager();
        Drawable appIcon = null;
        try {
            ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);
            appIcon = applicationInfo.loadIcon(pm);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return appIcon;
    }

    public static long getAppSize(Context context, String packageName) {
        long appSize = 0;
        try {
            ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(packageName, 0);
            appSize = new File(applicationInfo.sourceDir).length();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return appSize;
    }
}
